package org.bbelovic.devel.exercises;

public abstract class NumberExercises {

    public static long sum(final long n) {
        checkInputNumber(n);
        long result = 0L;
        for (int i = 1; i <= n; i++) {
            result = result + i;
        }
        return result;
    }

    public static long fact(final long n) {
        checkInputNumber(n);
        long result = 1L;
        if (n == 0L || n == 1L) {
            return result;
        } else {
            for (int i = 1; i <=n; i++) {
                result = result * i;
            }
            return result;
        }
    }

    public static long sqrt(final long n) {
        long result = 0L;
        for (int i = 0; i*i <= n; i++)
            result = i;
        return result;
    }

    public static int sumOfNumberDigits(int n) {
        int result = 0;
        while (n != 0) {
            result += n % 10;
            n /= 10;
        }
        return result;
    }

    public static int countOccurencesInNumber(int n, int what) {
        int result = 0;
        while (n != 0) {
            int digit = n % 10;
            n /= 10;
            if (digit == what) result++;
        }
        return result;
    }

    public static long reverseNumber(long n) {
        long result = 0L;
        while (n != 0) {
            long digit = n % 10;
            n /= 10;
            result = result * 10 + digit;
        }
        return result;
    }

    public static boolean isValidBirthNumber(long birthNumber) {
        return birthNumber % 11 == 0;
    }

    private static void checkInputNumber(final long n) {
        if (n < 0L) {
            throw new IllegalArgumentException("input must be >= than zero");
        }
    }
}
